package mainService.services;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import mainService.HTTPService;
import mainService.ServiceParams;
import mainService.data.IpClient;
import mainService.data.UsersConnected;
import databaseManager.connection.ConnectionManager;
import databaseManager.connection.IConnection;

/**
 * Servizio di Modifica della password dell'utente
 * 
 * @author Daniel Procop, Mattia Grecchi
 */
public class ModificaPasswordService implements HTTPService {

	@Override
	public ArrayList<String> getServiceResult(ServiceParams params) {

		String password = params.getValue("password");
		String nuovaPassword = params.getValue("nuovaPassword");
		String username = UsersConnected.getUsersConnected().getUtente(IpClient.getSingleton().getIp()).getUsername();

		// Load server
		IConnection manager = new ConnectionManager();
		manager.connect();

		Connection conn = manager.getConnection();

		try {
			Statement stmt = conn.createStatement();

			String qry = "SELECT password from users where username='"
					+ username + "' and password='"+password+"'";

			ResultSet rs = stmt.executeQuery(qry);

			if(!rs.first()){
				return getPagina(params, "passwordNonCorretta.html");
			}
						

			String cmd = "UPDATE users SET password='"+nuovaPassword+"'Where  username= '"+username+"'";
					
			if (stmt.executeUpdate(cmd) == 0) {// update non corretta
				return getPagina(params, "erroreCambioPassword.html");
			}
			else {
				return getPagina(params, "passwordCambiata.html");
			}
			

		} catch (SQLException e) {
			e.printStackTrace();
			return getPagina(params, "erroreCambioPassword.html");
		}
	}

	// restituisce pagina
	private ArrayList<String> getPagina(ServiceParams params, String pagina) {
		params.addParam("file", pagina);
		return (new HttpFileServer()).getServiceResult(params);
	}
}
